package pers.karl.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @version: V1.0
 */
public class ExcelWebUtil {

    /**
     * 导出excel
     *
     * @param workbook 工作簿
     * @param fileName 文件名（不需要带扩展名）
     * @return ResponseEntity 响应信息消息体
     * @throws IOException
     */
    public static ResponseEntity export(Workbook workbook, String fileName) throws IOException {

        if (workbook == null) {
            throw new IllegalArgumentException("workbook is null");
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("fileName is empty");
        }

        fileName += ".xls";
        if (workbook instanceof XSSFWorkbook) {
            fileName = fileName + "x";
        }

        // set file name
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.CREATED);
    }

}
